package com.zecan.rabbitmq.rabbitmq.contrller;

import com.zecan.rabbitmq.rabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: lenovo
 * \* Date: 2022/4/20
 * \* Time: 14:59
 * \* Description:
 * \
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {

        rabbitTemplate.convertAndSend("X", "XA", "10sTTL=" + message);
        rabbitTemplate.convertAndSend("X", "XB", "40sTTL=" + message);
        log.info("当前时间:{}, 发送一条消息:{}", new Date(), message);
    }


    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message") String message, @PathVariable("ttlTime") String ttlTime) {
        log.info("当前时间:{}, 发送延时时间为{}的一条消息:{}", new Date().toString(), ttlTime, message);

        /**
         * param1: 交换机名
         * param2: routingKey
         * param3: 发送的消息
         * param4: MessagePostProcessor类 可以设置消息信息
         */
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }

    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendDelayMsg(@PathVariable("message") String message,
                             @PathVariable("delayTime") Integer delayTime) {
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,
                DelayedQueueConfig.DELAYED_ROUTING_KEY,
                message, data -> {
                    data.getMessageProperties().setDelay(delayTime); //设置延时时间
                    return data;
                });
    }

}
